package com.example.blew.demo.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelWriter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * TODO
 * </p>
 *
 * @author chaodong.zeng@pcitc.com
 * @since 2022/8/19
 */


@Slf4j
@RestController
@RequestMapping("user")
@Api(tags = "helloWorld接口", value = "备注方法作用")
public class HelloWorld {

    @PostMapping("test")
    @ApiOperation(value = "hello")
    public String helloWord(){
        System.out.println("有人来");
        return "helloWord";
    }

    @GetMapping("testGet")
    public String testGet(){
        System.out.println("有人来");
        return "helloWord";
    }

    @GetMapping("session")
    @ApiOperation(value = "seesion测试")
    public void fun(HttpServletResponse response, HttpServletRequest request){
        HttpSession session = request.getSession();

    }


    @GetMapping("getImg")
    @ApiOperation(value = "图片测试")
    public void fun2(HttpServletResponse response, HttpServletRequest request){
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(130, 60, 4, 4);
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100,4,80);
        try {
//            captcha.write(response.getOutputStream());
            Image image = lineCaptcha.createImage("123");
            lineCaptcha.write(response.getOutputStream());
            HttpSession session = request.getSession();

            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }

class PtaPhyEntityQuery{

}




    @PostMapping(value = "exportData")
    @ApiOperation(value = "图片测试")
    public void exportData(HttpServletResponse response) throws IOException {
        String destFilePath = "/templates/example/PhyTemplates.xlsx";
        String copy = "/templates/example/copy.xlsx";
        // 复制一个模板文件出来
        FileUtil.copy(destFilePath, copy, false);
        // 1、拿到excle文件
        ExcelWriter writer = new ExcelWriter(copy);
        writer.setSheet(0);
        writer.passRows(1);
        // 2、填充列表
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=PhyTemplates.xls");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        IoUtil.close(out);

    }

    @PostMapping(value = "exportData1")
    @ApiOperation(value = "图片测试")
    public void exportData1(HttpServletResponse response) throws IOException {
        String destFilePath = "templates/example/templates.xlsx";
        String copy = "templates/example/copy.xlsx";
        String s = decodeFileNameByAgent(copy);

        // 复制一个模板文件出来
        try{
            FileUtil.copy(destFilePath, s, false);
        }catch (Exception e)
        {
            log.info("ssss",e.toString());
        }
        // 1、拿到excle文件
        ExcelWriter writer = new ExcelWriter(destFilePath);
        writer.setSheet(0);
        writer.passRows(1);
        // 2、填充列表
        for(int i=0;i<10;i++){
            for(int j=0;j<10;j++)
            {
                writer.writeCellValue(i, j, "hello_world");
            }
        }

        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=PhyTemplates.xls");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        IoUtil.close(out);
        FileUtil.del(copy);
    }


    public  String decodeFileNameByAgent(String fileName) {
        try {
            String browserCode = getBrowserCode();
            if (browserCode.contains("chrome")) {
                return URLEncoder.encode(fileName, "utf-8");
            } else if (browserCode.contains("trident")) {
                return URLEncoder.encode(fileName, "utf-8");
            } else {
                return browserCode.contains("gecko") ? "=?utf-8?B?" + Base64.encode(fileName.getBytes(StandardCharsets.UTF_8)) + "?=" : URLEncoder.encode(fileName, "utf-8");
            }
        } catch (Throwable var2) {
            try {
                throw var2;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return  null;
    }

    @PostMapping(value = "exportData2")
    @ApiOperation(value = "下载模板")
    public void exportData2(HttpServletResponse response) throws IOException {
        String destFilePath = "templates/example/templates.xlsx";
        List<String> rows=new ArrayList<>();
        rows.add("11111");
        rows.add("11111");
        rows.add("11111");
        rows.add("11111");
        // 1、拿到模板
        File template=new File(destFilePath);

        try{
            FileInputStream fileInputStream = new FileInputStream(template);
            //因为操作的是xlsx，所以使用XSSFWorkbook
            XSSFWorkbook wb = new XSSFWorkbook(fileInputStream);
            XSSFSheet sheet = wb.getSheetAt(0);
            //公式强制执行
            sheet.setForceFormulaRecalculation(true);
            //填充数据的逻辑了，举个例子而已，其他逻辑不展示
            for (int i = 0; i < rows.size(); i++) {

                sheet.getRow(i + 1).getCell(1).setCellValue("null".equals(rows.get(0)) ? "" : rows.get(0));

            }
            FileOutputStream output = new FileOutputStream(destFilePath);
            wb.write(output);//写入磁盘保存文件
            output.close();
//            downloadResourceFile(response,destFilePath);

        }catch (Exception e) {
            System.out.println(e);
        }

    }

//    private void downloadResourceFile(HttpServletResponse response, String filePath) throws IOException {
//        OutputStream out = null;
//        InputStream in = null;
//        org.springframework.core.io.ClassPathResource classPathResource = new ClassPathResource(filePath);
//        String fileName = decodeFileNameByAgent(FileNameUtil.getName(filePath));
//        response.setContentType("application/force-download");
//        response.setCharacterEncoding("utf-8");
//        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
//
//        try {
//            in = classPathResource.getInputStream();
//            out = response.getOutputStream();
//            IoUtil.copy(in, out);
//        } finally {
//            IoUtil.close(in);
//            IoUtil.close(out);
//        }
//
//    }


//    private String decodeFileNameByAgent(String fileName) {
//        try {
//            String browserCode = getBrowserCode();
//            if (browserCode.contains("chrome")) {
//                return URLEncoder.encode(fileName, "utf-8");
//            } else if (browserCode.contains("trident")) {
//                return URLEncoder.encode(fileName, "utf-8");
//            } else {
//                return browserCode.contains("gecko") ? "=?utf-8?B?" + Base64.encode(fileName.getBytes(StandardCharsets.UTF_8)) + "?=" : URLEncoder.encode(fileName, "utf-8");
//            }
//        } catch (Throwable var2) {
//            try {
//                throw var2;
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//        }
//        return "";
//    }

    private String getBrowserCode() {
        return getRequest().getHeader("User-Agent").toLowerCase();
    }

    private HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        if (servletRequestAttributes != null) {
            request = servletRequestAttributes.getRequest();
        }

        return request;
    }





}